﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

public class FileAnalyzer
{
    public static event Action<int, int, int, int> setNum;
    public static void AnalyzeFile(string fileName,out string[] words, out string[] frequencies)
    {
        // 读取文件内容
        string[] lines = File.ReadAllLines(fileName);

        // 统计原始文件的行数和单词数
        int originalLineCount = lines.Length;
        int originalWordCount = CountWords(lines);

        // 删除注释和空行
        lines = RemoveCommentsAndEmptyLines(lines);

        // 统计格式化后文件的行数和单词数
        int formattedLineCount = lines.Length;
        int formattedWordCount = CountWords(lines);

        // 统计每个单词的出现次数
        Dictionary<string, int> wordFrequency = CountWordFrequency(lines);

        // 将单词和出现次数排序
        var sortedWordFrequency = wordFrequency.OrderByDescending(kv => kv.Value);

        // 提取单词和出现次数到数组
        words = sortedWordFrequency.Select(kv => kv.Key).ToArray();
        frequencies = sortedWordFrequency.Select(kv => kv.Value.ToString()).ToArray();

        setNum(originalLineCount, originalWordCount, formattedLineCount, formattedWordCount);

    }

    private static int CountWords(string[] lines)
    {
        int wordCount = 0;
        foreach (var line in lines)
        {
            string[] words = line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
            wordCount += words.Length;
        }
        return wordCount;
    }

    private static string[] RemoveCommentsAndEmptyLines(string[] lines)
    {
        List<string> cleanedLines = new List<string>();
        foreach (var line in lines)
        {
            string trimmedLine = line.Trim();
            if (!string.IsNullOrEmpty(trimmedLine) && !trimmedLine.StartsWith("//"))
            {
                cleanedLines.Add(trimmedLine);
            }
        }
        return cleanedLines.ToArray();
    }

    private static Dictionary<string, int> CountWordFrequency(string[] lines)
    {
        Dictionary<string, int> wordFrequency = new Dictionary<string, int>();
        foreach (var line in lines)
        {
            string[] words = Regex.Split(line, @"\W+");
            foreach (var word in words)
            {
                if (!string.IsNullOrWhiteSpace(word))
                {
                    string cleanedWord = word.ToLower();
                    if (wordFrequency.ContainsKey(cleanedWord))
                    {
                        wordFrequency[cleanedWord]++;
                    }
                    else
                    {
                        wordFrequency[cleanedWord] = 1;
                    }
                }
            }
        }
        return wordFrequency;
    }
}
